<template>
  <div id="manageTestView">
    <a-card class="manageTestList">
      <div class="header">
        <h2>比赛列表</h2>
        <a-button
          class="addTest"
          type="primary"
          @click="addExam"
          :style="{ background: '#065ACC' }"
          >创建比赛</a-button
        >
      </div>
      <a-table
        :columns="columns"
        :data="exams"
        :pagination="{
          showTotal: true,
          hideOnSinglePage: true,
        }"
        :bordered="{ wrapper: true, cell: true }"
        stripe
      >
        <template #isPublic="{ record }">
          <a-tag v-if="record.isPublic" color="blue" bordered> 未开始 </a-tag>
          <a-tag v-else color="gray" bordered> 已结束 </a-tag>
        </template>
        <template #testName="{ record }">
          <a-Link href="#" @click="goToDisplay(record.id)">
            {{ record.courseName }}
          </a-Link>
        </template>
        <template #dueDate="{ record }">
          {{ formatDate(record.dueDate) }}
        </template>
        <template #scoreWeight="{ record }">
          {{ record.scoreWeight }}
        </template>
        <template #questionCount> 20题 </template>
        <template #humanName="{ record }">
          {{ record.title }}
        </template>
        <template #operation="{ record }">
          <a-space>
            <a-tooltip position="bottom" content="编辑" mini>
              <icon-edit
                :style="{ fontSize: '18px', color: '#0A65CC' }"
                @click="openEditForm(record)"
              />
            </a-tooltip>
            <a-tooltip position="bottom" content="删除" mini>
              <icon-delete
                :style="{ fontSize: '18px', color: 'red' }"
                @click="deleteExam(record.id)"
              />
            </a-tooltip>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <!-- 编辑表单 -->
    <div id="editTestView">
      <a-drawer
        :visible="isEditFormVisible"
        @cancel="closeEditForm"
        :width="600"
        :footer="false"
      >
        <template #title>
          <div>修改比赛</div>
        </template>
        <a-form :model="editForm">
          <a-form-item field="courseName" label="比赛名称">
            <a-input
              v-model="editForm.courseName"
              placeholder="请输入比赛名称"
              class="titleInput"
            />
          </a-form-item>
          <a-form-item field="dueDate" label="起始时间">
            <a-DatePicker v-model="editForm.dueDate" />
          </a-form-item>
          <a-form-item field="scoreWeight" label="持续时长">
            <a-input-number
              placeholder="请输入持续时长"
              v-model="editForm.scoreWeight"
              min="{0}"
              max="{100}"
              class="titleInput"
            />
          </a-form-item>
          <a-form-item field="title" label="举办者">
            <a-input
              v-model="editForm.title"
              placeholder="请输入举办者"
              class="titleInput"
            />
          </a-form-item>
          <a-form-item field="isPublic" label="状态">
            <a-select v-model="editForm.isPublic" :style="{ width: '160px' }">
              <a-option :value="true">未开始</a-option>
              <a-option :value="false">已结束</a-option>
            </a-select>
          </a-form-item>
          <a-divider />
          <div style="margin-top: 16px" />
          <a-form-item>
            <a-button
              type="primary"
              style="min-width: 200px"
              @click="submitEditForm"
              >提交
            </a-button>
            <a-button
              type="outline"
              style="min-width: 200px; margin-left: 16px"
              @click="goToSelection"
              >修改题目
            </a-button>
          </a-form-item>
        </a-form>
      </a-drawer>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { IconDelete, IconEdit } from "@arco-design/web-vue/es/icon";
import { Message } from "@arco-design/web-vue";
import { useStore } from "vuex";

const store = useStore();
const exams = ref([]);
const isEditFormVisible = ref(false);
const editForm = ref({
  id: null,
  courseName: "",
  dueDate: "",
  scoreWeight: "",
  title: "",
  isPublic: true,
});

const router = useRouter();

const columns = [
  {
    title: "状态",
    slotName: "isPublic",
  },
  {
    title: "比赛名称",
    slotName: "testName",
  },
  {
    title: "起始时间",
    slotName: "dueDate",
  },
  {
    title: "持续时长",
    slotName: "scoreWeight",
  },
  {
    title: "题数",
    slotName: "questionCount",
  },
  {
    title: "举办者",
    slotName: "humanName",
  },
  {
    title: "操作",
    slotName: "operation",
  },
];

const formatDate = (date) => {
  const options = {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  };
  return new Date(date).toLocaleDateString("zh-CN", options);
};

onMounted(async () => {
  store.commit("loading/showLoading", true);
  try {
    const response = await fetch("http://localhost:8121/api/examination/all");
    exams.value = await response.json();
    store.commit("loading/showLoading", false);
  } catch (error) {
    console.error("Failed to fetch examinations:", error);
  }
});

const openEditForm = (exam) => {
  editForm.value = { ...exam };
  isEditFormVisible.value = true;
};

const closeEditForm = () => {
  isEditFormVisible.value = false;
};

const submitEditForm = async () => {
  try {
    const response = await fetch(
      `http://localhost:8121/api/examination/update`,
      {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(editForm.value),
      },
    );
    if (response.ok) {
      const index = exams.value.findIndex(
        (exam) => exam.id === editForm.value.id,
      );
      exams.value[index] = { ...editForm.value };
      Message.success("比赛信息已更新");
      closeEditForm();
    } else {
      Message.error("更新失败");
    }
  } catch (error) {
    console.error("更新失败:", error);
    Message.error("更新过程中发生错误");
  }
};

const deleteExam = async (id) => {
  const confirmed = confirm("确定要删除这场比赛吗？");
  if (confirmed) {
    try {
      const response = await fetch(
        `http://localhost:8121/api/examination/delete/${id}`,
        {
          method: "DELETE",
        },
      );
      if (response.ok) {
        exams.value = exams.value.filter((exam) => exam.id !== id);
        Message.success("比赛已删除");
      } else {
        Message.error("删除失败");
      }
    } catch (error) {
      console.error("删除失败:", error);
      Message.error("删除过程中发生错误");
    }
  }
};

const addExam = () => {
  router.push("/manage/test/register");
};

// 跳转到 display 页面
const goToDisplay = (examId) => {
  router.push(`/manage/test/display/${examId}`);
};

// 跳转到 selection 页面
const goToSelection = () => {
  router.push("/manage/test/selection");
};
</script>

<style scoped>
#manageTestView {
  max-width: 1440px;
  margin: 0 auto;
  display: flex;
  flex-direction: row;
}
.manageTestList {
  flex: 1;
  margin-right: 8px;
}
.header {
  display: flex;
  justify-content: space-between;
  margin: 0 6px;
}
.addTest {
  display: flex;
  align-self: center;
}
#editTestView {
  max-width: 600px;
  margin: auto;
}
.titleInput {
  width: 100%;
}
</style>
